<style lang="less">
@import url(../../../node_modules/@wangeditor/editor/dist/css/style.css);
@import "@/assets/style/variables.less";

.publish-article {
    width: 100%;
    height: 100%;
    min-height: 1150px;
    background-color: #fff;
    border-radius: @border-radius;
    box-shadow: @box-shadow;
    padding: @padd;


    .publish-article-header {
        width: 100%;
        height: 100%;

        .opt {
            margin-bottom: 15px;
        }
    }

    .my-select {
        margin-left: 15px;
    }

    .preview-img {
        width: 360px;
        height: 180px;
    }

    .el-upload-list {
        display: none;
    }
}
</style>
<template>
    <div class="publish-article">
        <header class="publish-article-header">
            <div class="opt">
                <el-input v-model="article.title" placeholder="请输入文章标题"></el-input>
            </div>

            <div class="opt">
                <el-input v-model="article.author" placeholder="请输入作者"></el-input>
            </div>

            <div class="opt">
                <el-select @change="changeCateFn" v-model="article.cate" placeholder="请选择">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>

                <el-select v-if="category_options.length != 0" class="my-select" v-model="article.category"
                    placeholder="请选择">
                    <el-option v-for="item in category_options" :key="item.value" :label="item.label"
                        :value="item.value">
                    </el-option>
                </el-select>
            </div>

            <div class="opt">
                <!-- 富文本框 -->
                <div style="border: 1px solid #ccc;">
                    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig"
                        :mode="mode" />
                    <Editor style="height: 500px; overflow-y: hidden;" v-model="html" :defaultConfig="editorConfig"
                        :mode="mode" @onCreated="onCreated" />
                </div>
            </div>

            <div class="opt" style="display: flex;">
                <el-upload class="upload-demo" drag action="" :on-change="changeFn" :autoUpload="false">
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>

                <div v-if="src" class="opt-right" style="text-align: center; margin-left: 15px">
                    <img class="preview-img" :src="src" alt="">
                </div>
            </div>

            <div class="opt">
                <el-input v-model="article.tag" placeholder="标签"></el-input>
            </div>

            <div class="opt">
                <el-button type="primary" @click="submitFn">点击发布</el-button>
            </div>
        </header>
    </div>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
// import { IEditorConfig } from '@wangeditor/editor'
import { listCate, uploadPhoto, publishArticle, host } from "../../api/index"
import { Message } from 'element-ui';

export default {
    components: { Editor, Toolbar },
    data() {
        return {
            article: {
                title: "",
                author: "",
                cate: "",
                category: "",
                tag: "",
            },
            options: [],
            category_options: [
                // {
                //     value: '选项1',
                //     label: '职场'
                // },
            ],
            // 富文本框的变量
            editor: null,
            html: '',// 富文本框输入的文本（html）
            toolbarConfig: {},  // 显示哪些工具按钮 显示所有默认工具按钮

            // 在富文本框中做图片上传的配置
            editorConfig: {
                placeholder: '请输入内容...',
                MENU_CONF: {
                    uploadImage: {
                        server: `${host}/api/photo/upload_img`,
                        fieldName: 'photo',
                    }
                }
            },
            // 富文本框的模式  default 模式（默认模式）;  simple 模式（简洁模式）
            mode: 'default',
            src: "",// 文本封面图片
            cateArr: [],
            file: null,// 图片文件对象
        }
    },
    methods: {
        // 上传图片返回路径
        async uploadPhotoFn() {
            if (this.file) {
                let formData = new FormData()
                formData.append("photo", this.file)
                return await uploadPhoto(formData)
            }

        },
        // 选择一级菜单
        changeCateFn(value) {
            // console.log("--->", value)
            this.article.cate = value;
            let arr = this.cateArr.filter(item => {
                return item.cate == value;
            })
            let newArr = arr.map(item => {
                return {
                    value: item.cate_name,
                    label: item.cate_name,
                }
            })
            this.category_options = newArr;
            // 初始值
            this.article.category = arr[0] && arr[0].cate_name;
            // console.log('111', this.article);
        },
        // 编写方法 获取导航列表
        async listCateFn() {
            await listCate().then(
                resData => {
                    // console.log(resData);
                    if (resData.code == 200) {
                        let { result } = resData;
                        this.cateArr = result;
                        // console.log(this.cateArr);
                        // 使用扩展运算符 (...) 将 Set 对象转换为数组
                        const cateArr = [...new Set(result.map(item => item.cate))];
                        this.options = cateArr.map(cate => {
                            return {
                                value: cate,
                                label: cate
                            }
                        })
                    }
                }
            )
        },
        // 富文本框的方法
        onCreated(editor) {
            // console.log(`${host}/api/photo/upload_img`)
            this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错

        },
        // 选择封面图片
        changeFn(info) {
            // 读取单个文件
            let file = info.raw;
            const reader = new FileReader();
            reader.onload = () => {
                // 将图像文件转换为 Base64 字符串
                this.src = reader.result;
            }
            if (file) {
                reader.readAsDataURL(file);
                this.file = file;
            }
            return false;
        },
        // 获取标题、作者、分类菜单、文章内容、封面图、标签
        async submitFn() {
            // 富文本框的值
            let html = this.html;
            // 记录图片信息
            let result = await this.uploadPhotoFn();
            // console.log(result)
            // 解构赋值
            let { title, author, cate, category, tag } = this.article;
            if (title && author && cate && category && tag && html && result.picUrl) {
                // console.log({title, author, cate, cate_name: category, content:html, src: result.picUrl, tag})
                // 发布文章
                await publishArticle({ title, author, cate, cate_name: category, content: html, src: result.picUrl, tag })
                    .then(
                        resData => {
                            //  console.log(resData);
                            // 发布成功
                            if (resData.code == 200) {
                                Message({ type: "success", message: resData.msg })
                                this.$router.push({ path: "/article_list" })
                            }
                            //  发布失败
                            else {
                                Message({ type: "error", message: resData.msg })
                            }
                        }
                    )
            }
            else {
                // 缺少参数
                Message({ type: "error", message: "缺少参数" })
            }

        }
    },
    beforeDestroy() {
        const editor = this.editor
        if (editor == null) return
        editor.destroy() // 组件销毁时，及时销毁编辑器
    },
    created() {
        // 初始化
        this.$store.commit("addTab", this.$route);
        this.listCateFn();

    },
    watch: {
        $route: {
            immediate: true,
            deep: true,
            handler(newRoute) {
                // console.log(newRoute);
                this.$store.commit("addTab", newRoute);
            }
        }
    }

}


</script>